前一天30天Flutter手滑系列 - 聊天室開發(Chat Room)(2)在除錯上花了不少時間,今天繼續優化及開發新功能。
為了讓成功登入有訊息提醒,我們快加入fluttertoast這個套件。
成功後效果就會如下:
然後我們登入成功後可以導回首頁,可以加入以下程式碼
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyHomePage(currentUserId: user.uid)));
到目前為止的程式碼如下
class LoginPageState extends State<LoginPage> {
final GoogleSignIn _googleSignIn = GoogleSignIn();
final FirebaseAuth _auth = FirebaseAuth.instance;
SharedPreferences prefs;
FirebaseUser currentUser;
Future<FirebaseUser> _handleSignIn() async {
prefs = await SharedPreferences.getInstance();
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
final FirebaseUser user =
(await _auth.signInWithCredential(credential)).user;
print("signed in " + user.displayName);
if (user != null) {
// 檢查是否登入
final QuerySnapshot result = await Firestore.instance
.collection('users')
.where('id', isEqualTo: user.uid)
.getDocuments();
final List<DocumentSnapshot> documents = result.documents;
if (documents.length == 0) {
// 如果是新使用者就更新
Firestore.instance.collection('users').document(user.uid).setData({
'nickname': user.displayName,
'photoUrl': user.photoUrl,
'id': user.uid,
'createdAt': DateTime.now().millisecondsSinceEpoch.toString(),
'chattingWith': null
});
// 把資料存到本地端
currentUser = user;
await prefs.setString('id', currentUser.uid);
await prefs.setString('nickname', currentUser.displayName);
await prefs.setString('photoUrl', currentUser.photoUrl);
} else {
// 把資料存到本地端
await prefs.setString('id', documents[0]['id']);
await prefs.setString('nickname', documents[0]['nickname']);
await prefs.setString('photoUrl', documents[0]['photoUrl']);
await prefs.setString('aboutMe', documents[0]['aboutMe']);
}
Fluttertoast.showToast(msg: "Sign in success");
Navigator.push(context, MaterialPageRoute(builder: (context) => MyHomePage(currentUserId: user.uid)));
} else {
Fluttertoast.showToast(msg: "Sign in fail");
}
return user;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SIGN IN'),
),
body: Center(
child: RaisedButton(
child: Text('SIGN IN WITH GOOGLE'),
onPressed: () {
_handleSignIn()
.then((FirebaseUser user) => print(user))
.catchError((e) => print(e));
}),
));
}
}
https://pub.dev/packages/firebase_auth